# -*- coding: utf-8 -*-
"""Presenter for Add Words screen

gamestate.players must be Players
gamestate.players.players must be list of Players
gamestate.current_added_player must be Player
gamestate.current_added_player.name must be string
gamestate.current_added_player.words must be empty list or list of valid words
gamestate.settings.word_number must be int
gamestate.hat must be None or valid Hat
"""
from kivy.uix.gridlayout import GridLayout
from kivy.properties import NumericProperty, StringProperty, ListProperty
from model.gamestate import Word, Phase, Hat
from model.dictionary import Dictionary
from ui.hat_widget import HatWidget


class AddWords(HatWidget):
    """Root widget

    """
    next_button_text = StringProperty()
    player_name = StringProperty()
    word_count = NumericProperty()
    cur_count = NumericProperty()

    def __init__(self, gamestate=None, presenter=None, **kwargs):
        """Constructor interface for MainView"""
        self.gamestate = gamestate
        self.presenter = presenter
        self.player = self.gamestate.current_added_player
        self.player_name = self.player.name
        self.word_count = self.gamestate.settings.words_number
        self.words = self.player.words
        self.cur_count = len(self.words)
        super(AddWords, self).__init__(**kwargs)
        self.word_list.bind(minimum_height=self.word_list.setter('height'))
        self.update_button_text()
        for word in self.words:
            self.word_list.draw_word(word.text)

    def finish(self):
        """Finish entering words"""
        self.gamestate.players.add(self.player)
        self.gamestate.current_added_player = None
        if self.gamestate.hat is None:
            self.gamestate.hat = Hat([])
        for word in self.words:
            self.gamestate.hat.words.append(word)
        self.presenter.change_phase(Phase.START_GAME)

    def from_dict(self):
        """Fill word list with words from dictionary"""
        count = self.word_count - self.cur_count
        dict_ = Dictionary.get_dict(None)
        deny_words = []
        for word in self.words:
            deny_words.append(word.text)
        l = dict_.get_words(count, deny_words)
        for word in l:
            self.word_list.add_word(word)
        self.set_buttons_state()
        self.update_button_text()

    def add_user_word(self, input_):
        """Add single word from user's input"""
        if len(self.words) == self.word_count:
            return
        self.word_list.on_add_word(input_)
        self.set_buttons_state()
        self.update_button_text()

    def del_word(self, word):
        """"""
        self.word_list.del_word(word)
        self.set_buttons_state()
        self.update_button_text()

    def set_buttons_state(self):
        """Enables and disables buttons depending on words count"""
        if len(self.words) == self.word_count:
            self.add_word_but.enabled = False
            self.add_dict_but.enabled = False
        else:
            self.add_word_but.enabled = True
            self.add_dict_but.enabled = True

    def update_button_text(self):
        words_counter = str(len(self.words)) + '/' + \
            str(self.word_count)
        if len(self.words) < self.word_count * 0.4:
            self.next_button_text = words_counter
            self.next_butt.enabled = False
            self.next_butt.color = [1, 1, 1, 1]
        else:
            if len(self.words) < self.word_count:
                self.next_button_text = u'{} ({})'.format(_('Next'),
                                                          words_counter)
                self.next_butt.color = [0, 0.5, 0, 1]
            else:
                self.next_button_text = _('Next')
                self.next_butt.color = [0, 1, 0, 1]
            self.next_butt.enabled = True

    def go_back(self):
        self.presenter.change_phase(Phase.ADD_PLAYER)

    def plus_butt_up(self, val):
        """
        WTF? unused method?
        """
        if val.strip() == '':
            self.add_word_but.enabled = False
        else:
            self.add_word_but.enabled = True


class ListElement(GridLayout):
    """Widget for element of list

    Consists of word label and deleting button
    """
    pass


class WordList(GridLayout):
    """Widget for word list

    Container under ScrollView
    """

    def on_add_word(self, input_):
        """Handle clicking on plus button

        Args:
        input_: (TextInput) input with word text
        """
        self.add_word(input_.text)
        input_.text = ''

    def add_word(self, text):
        """Add word to list

        Args:
        text: (unicode) word text
        """
        if not text or self.parent.cur_count >= self.parent.word_count:
            return
        self.parent.words.append(Word(self.parent.player,
                                      text))
        self.draw_word(text)

    def draw_word(self, text):
        """Displays word in lists

        Args:
        text: (unicode) word text
        """
        self.parent.cur_count += 1
        el = ListElement()
        el.word = text
        self.add_widget(el)

    def del_word(self, word):
        """Delete word from list

        Args:
        word: (ListElement) representing word to be deleted
        """
        text = word.word
        for i in range(len(self.parent.words)):
            if self.parent.words[i].text == text:
                self.parent.words.pop(i)
                break
        self.remove_widget(word)
        self.parent.cur_count -= 1
